<!-- comment 子组件 -->
<template>
  <div class="cmt-container">
    <h3>发表评论</h3>
    <hr>
    <textarea placeholder="请输入拼了内容（最多120字）" maxlength="120" v-model="content"></textarea>
    <mt-button type="primary" size="large" @click="submitCmt">发表评论</mt-button>
    <div class="cmt-list">
      <div class="cmt-item" v-for="(item, index) in commentList" :key="item.add_time">
        <div class="cmt-title">
        第{{ index+1 }}楼&nbsp;&nbsp;用户： {{ item.user_name}}&nbsp;&nbsp;发表时间： {{ item.add_time | dataFormat }}
      </div>
      <div class="cmt-body" v-text="item.content==='undefined'?'此用户很懒，什么也没留下':item.content"></div>
      </div>
    </div>
    <mt-button type="danger" size="large" plain @click="loadMore">加载更多</mt-button>
  </div>
</template>

<script>
  import { Toast } from "mint-ui";
  export default {
    data() {
      return {
        pageIndex: 1,
        commentList: [],
        content: ''
      }
    },
    props: ["id"],
    created () {
     this.getComments()
    },
    methods: {
      getComments() { // 获取评论数据
        this.axios.get('api/getcomments/'+this.id+'?pageindex='+this.pageIndex)
        .then( resp => {
          if (resp.data.status ===0) { // 获取数据成功
            this.commentList = this.commentList.concat(resp.data.message);
          }else { // 获取失败
            Toast('获取数据失败')
          }
          
        })
      },
      loadMore() { // 加载更多
        this.pageIndex++
        this.getComments()
      },
      submitCmt() { // 提交评论
        if (this.content.trim().length === 0) {
          return Toast('评论内容不能为空')
        }
        this.axios.post('api/postcomment/'+this.id, {content: this.content}).then( 
          resp => {
            if (resp.data.status === 0) {
              Toast(resp.data.message)
              let cmt = { user_name: '匿名用户', add_time: Date.now(), content: this.content.trim()}
              this.commentList.pop()
              this.commentList.unshift(cmt)
              this.content = ''
            }else {
               Toast('resp.data.message')
            }
          })
      }
    }
  }
</script>

<style lang='scss' scoped>
  .cmt-container {
    h3 {
      font-size: 18px;
    }
    textarea {
      margin: 0;
      font-size: 14px;
      height: 85px;
    }
    .cmt-list {
      margin: 15px 0;
      .cmt-item {
        line-height: 30px;
        .cmt-title {
        font-size: 14px;
        background-color: #ccc;
      }
      .cmt-body {
        font-size: 12px;
        text-indent: 2em;
      }
      }
    }
  }
</style>